package com.example.administrator.kotiln.ui;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.administrator.kotiln.R;
import com.example.administrator.kotiln.base.BaseActivity;
import com.example.administrator.kotiln.bean.Test_Socket_Data;
import com.example.administrator.kotiln.utils.Share;
import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/9/16.
 */

public class SocketActivity extends BaseActivity {

    private Button socket_bt;
    private TextView socket_msg;

    Socket socket = null;
    String buffer = "";
    EditText socket_send;
    String geted1;
    public Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0x11) {
                Bundle bundle = msg.getData();
                socket_msg.append("server:" + bundle.getString("msg") + "\n");
            }
        }

    };


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_socket);

        initView();

    }

    private void initView() {
        socket_bt = (Button) findViewById(R.id.socket_bt);
        socket_msg = (TextView) findViewById(R.id.socket_msg);
        socket_send = (EditText) findViewById(R.id.socket_send);
        ImageView back = (ImageView) findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        socket_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                geted1 = socket_send.getText().toString();
                socket_msg.append("client:" + geted1 + "\n");
                //启动线程 向服务器发送和接收信息
                new MyThread(geted1).start();
            }
        });
    }

    class MyThread extends Thread {

        public String txt1;

        public MyThread(String str) {
            txt1 = str;
        }

        @Override
        public void run() {
            //定义消息
            Message msg = new Message();
            msg.what = 0x11;
            Bundle bundle = new Bundle();
            bundle.clear();
            try {

                //连接服务器 并设置连接超时为5秒
                Share.d("连接中……");
                socket = new Socket();
                // 创建Socket对象 & 指定服务端的IP 及 端口号
                //方法一
                // socket = new Socket("192.168.1.240", 1396);
                // socket.setSoTimeout(10000);
                //方法二
                socket.connect(new InetSocketAddress("192.168.1.240", 9505), 10000);

                Share.d("链接成功");
                //获取输入输出流
                OutputStream ou = socket.getOutputStream();

                //接收服务器发送的数据
                BufferedReader bff = new BufferedReader(new InputStreamReader(
                        socket.getInputStream()));
                //读取发来服务器信息
                String line = null;
                buffer = "";
//                while ((line = bff.readLine()) != null) {
//                    buffer = line + buffer;
//                }

                // 步骤2：写入需要发送的数据到输出流对象中
                List<Test_Socket_Data> list = new ArrayList<Test_Socket_Data>();
                list.add(new Test_Socket_Data("test", txt1));
                Gson gson = new Gson();
                String line1 = gson.toJson(list);
                Share.d("连接发送" + line1);
                ou.write((line1 + "\n").getBytes("utf-8"));
                // Share.d("连接发送" + txt1);
                // 步骤3：发送数据到服务端
                ou.flush();
                bundle.putString("msg", buffer.toString());
                Share.d("连接返回" + buffer.toString());
                msg.setData(bundle);
                //发送消息 修改UI线程中的组件
                myHandler.sendMessage(msg);
                //关闭各种输入输出流
                bff.close();
                ou.close();
                socket.close();
            } catch (SocketTimeoutException aa) {
                //连接超时 在UI界面显示消息
                bundle.putString("msg", "服务器连接失败！请检查网络是否打开");
                msg.setData(bundle);
                //发送消息 修改UI线程中的组件
                myHandler.sendMessage(msg);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
